const path = require('path');
const dotenv = require('dotenv');

// 根据环境加载对应的配置文件
const env = process.env.NODE_ENV || 'development';
dotenv.config({ path: path.join(__dirname, `../../.env.${env}`) });

const config = {
  // 应用基础配置
  app: {
    name: process.env.APP_NAME || 'OKX Trading Robot',
    description: process.env.APP_DESCRIPTION || 'OKX自动交易机器人后端API',
    version: process.env.API_VERSION || 'v1',
    port: parseInt(process.env.PORT) || 3000,
    env: env,
    frontendUrl: process.env.FRONTEND_URL || 'http://localhost:3000',
    enableDebugMode: process.env.ENABLE_DEBUG_MODE === 'true',
    enableHotReload: process.env.ENABLE_HOT_RELOAD === 'true'
  },

  // 数据库配置
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT) || 3306,
    user: process.env.DB_USER || 'root',
    password: process.env.DB_PASSWORD || '',
    database: process.env.DB_NAME || 'okx_robot',
    connectionLimit: parseInt(process.env.DB_CONNECTION_LIMIT) || 10,
    acquireTimeout: parseInt(process.env.DB_ACQUIRE_TIMEOUT) || 60000,
    timeout: parseInt(process.env.DB_TIMEOUT) || 60000
  },

  // Redis配置
  redis: {
    host: process.env.REDIS_HOST || 'localhost',
    port: parseInt(process.env.REDIS_PORT) || 6379,
    password: process.env.REDIS_PASSWORD || '',
    db: parseInt(process.env.REDIS_DB) || 0,
    connectTimeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT) || 10000,
    retryDelay: parseInt(process.env.REDIS_RETRY_DELAY) || 1000,
    maxRetries: parseInt(process.env.REDIS_MAX_RETRIES) || 3
  },

  // JWT配置
  jwt: {
    secret: process.env.JWT_SECRET || 'your-super-secret-jwt-key',
    expiresIn: process.env.JWT_EXPIRE || '30d',
    refreshSecret: process.env.JWT_REFRESH_SECRET || 'your-super-secret-refresh-key',
    refreshExpiresIn: process.env.JWT_REFRESH_EXPIRE || '7d',
    issuer: process.env.JWT_ISSUER || 'okx-robot',
    audience: process.env.JWT_AUDIENCE || 'okx-robot-users'
  },

  // 会话配置
  session: {
    secret: process.env.SESSION_SECRET || 'your-session-secret',
    name: process.env.SESSION_NAME || 'okx_robot_session',
    cookie: {
      maxAge: parseInt(process.env.SESSION_COOKIE_MAX_AGE) || 86400000,
      secure: process.env.SESSION_COOKIE_SECURE === 'true',
      httpOnly: process.env.SESSION_COOKIE_HTTP_ONLY !== 'false',
      sameSite: process.env.SESSION_COOKIE_SAME_SITE || 'lax'
    }
  },

  // 日志配置
  logger: {
    level: process.env.LOG_LEVEL || 'info',
    filePath: process.env.LOG_FILE_PATH || './logs',
    maxSize: process.env.LOG_MAX_SIZE || '20m',
    maxFiles: process.env.LOG_MAX_FILES || '14d',
    format: process.env.LOG_FORMAT || 'combined'
  },

  // 邮件配置
  mail: {
    host: process.env.MAIL_HOST || 'smtp.gmail.com',
    port: parseInt(process.env.MAIL_PORT) || 587,
    user: process.env.MAIL_USER || '',
    pass: process.env.MAIL_PASS || '',
    from: process.env.MAIL_FROM || 'noreply@okxrobot.com',
    fromName: process.env.MAIL_FROM_NAME || 'OKX Robot',
    secure: process.env.MAIL_SECURE === 'true',
    requireTLS: process.env.MAIL_REQUIRE_TLS === 'true'
  },

  // 文件上传配置
  upload: {
    path: process.env.UPLOAD_PATH || './uploads',
    maxFileSize: parseInt(process.env.MAX_FILE_SIZE) || 5242880,
    allowedTypes: process.env.ALLOWED_FILE_TYPES?.split(',') || [
      'image/jpeg',
      'image/png',
      'image/gif',
      'application/pdf',
      'text/csv'
    ],
    tempDir: process.env.UPLOAD_TEMP_DIR || './temp'
  },

  // API限制配置
  rateLimit: {
    windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 900000,
    maxRequests: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100,
    skipSuccessfulRequests: process.env.RATE_LIMIT_SKIP_SUCCESSFUL_REQUESTS === 'true',
    skipFailedRequests: process.env.RATE_LIMIT_SKIP_FAILED_REQUESTS === 'true'
  },

  // OKX API配置
  okx: {
    apiKey: process.env.OKX_API_KEY || '',
    secretKey: process.env.OKX_SECRET_KEY || '',
    passphrase: process.env.OKX_PASSPHRASE || '',
    sandbox: process.env.OKX_SANDBOX === 'true',
    apiBaseUrl: process.env.OKX_API_BASE_URL || 'https://www.okx.com',
    wsUrl: process.env.OKX_WS_URL || 'wss://ws.okx.com:8443/ws/v5/public',
    requestTimeout: parseInt(process.env.OKX_REQUEST_TIMEOUT) || 30000
  },

  // WebSocket配置
  websocket: {
    port: parseInt(process.env.WS_PORT) || 3001,
    path: process.env.WS_PATH || '/ws',
    heartbeatInterval: parseInt(process.env.WS_HEARTBEAT_INTERVAL) || 30000,
    maxPayload: parseInt(process.env.WS_MAX_PAYLOAD) || 1048576
  },

  // 缓存配置
  cache: {
    ttl: parseInt(process.env.CACHE_TTL) || 3600,
    checkPeriod: parseInt(process.env.CACHE_CHECK_PERIOD) || 600,
    maxKeys: parseInt(process.env.CACHE_MAX_KEYS) || 1000
  },

  // 安全配置
  security: {
    bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS) || 12,
    password: {
      minLength: parseInt(process.env.PASSWORD_MIN_LENGTH) || 8,
      requireUppercase: process.env.PASSWORD_REQUIRE_UPPERCASE === 'true',
      requireLowercase: process.env.PASSWORD_REQUIRE_LOWERCASE === 'true',
      requireNumbers: process.env.PASSWORD_REQUIRE_NUMBERS === 'true',
      requireSymbols: process.env.PASSWORD_REQUIRE_SYMBOLS === 'true'
    }
  },

  // 监控配置
  monitoring: {
    enableMetrics: process.env.ENABLE_METRICS === 'true',
    metricsPort: parseInt(process.env.METRICS_PORT) || 9090,
    healthCheckInterval: parseInt(process.env.HEALTH_CHECK_INTERVAL) || 30000
  },

  // 任务调度配置
  scheduler: {
    timezone: process.env.CRON_TIMEZONE || 'Asia/Shanghai',
    enableScheduledTasks: process.env.ENABLE_SCHEDULED_TASKS === 'true'
  },

  // 开发工具配置
  devTools: {
    enableSwagger: process.env.ENABLE_SWAGGER === 'true'
  },

  // 默认管理员配置
  admin: {
    username: process.env.DEFAULT_ADMIN_USERNAME || 'admin',
    email: process.env.DEFAULT_ADMIN_EMAIL || 'admin@okxrobot.com',
    password: process.env.DEFAULT_ADMIN_PASSWORD || 'Admin123!',
    role: process.env.DEFAULT_ADMIN_ROLE || 'super_admin'
  }
};

// 验证必要的配置
const validateConfig = () => {
  const requiredFields = [
    'database.host',
    'database.user',
    'database.password',
    'database.database',
    'jwt.secret',
    'jwt.refreshSecret',
    'session.secret'
  ];

  const missingFields = requiredFields.filter(field => {
    const keys = field.split('.');
    let value = config;
    for (const key of keys) {
      value = value[key];
      if (value === undefined) return true;
    }
    return false;
  });

  if (missingFields.length > 0) {
    throw new Error(`Missing required configuration fields: ${missingFields.join(', ')}`);
  }
};

// 获取配置值
const get = (path) => {
  const keys = path.split('.');
  let value = config;
  for (const key of keys) {
    if (value && typeof value === 'object' && key in value) {
      value = value[key];
    } else {
      return undefined;
    }
  }
  return value;
};

// 设置配置值
const set = (path, value) => {
  const keys = path.split('.');
  let current = config;
  for (let i = 0; i < keys.length - 1; i++) {
    const key = keys[i];
    if (!(key in current) || typeof current[key] !== 'object') {
      current[key] = {};
    }
    current = current[key];
  }
  current[keys[keys.length - 1]] = value;
};

module.exports = {
  config,
  get,
  set,
  validateConfig
};
